package com.zzty.zzlp.controller;

import com.sun.org.apache.xpath.internal.operations.Bool;
import com.zzty.zzlp.commom.ChatFileUpLoad;
import com.zzty.zzlp.entity.*;
import com.zzty.zzlp.service.ChatService;
import com.zzty.zzlp.service.GroupService;
import com.zzty.zzlp.service.UserService;
import com.zzty.zzlp.socket.SessionUtils;
import com.zzty.zzlp.socket.SocketHandler;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.socket.TextMessage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("Group")
public class GroupController {

    @Autowired
    GroupService groupService;

    @Autowired
    UserService userService;

    @Autowired
    ChatService chatService;

    @Autowired
    private SocketHandler socketHandler;

    @RequestMapping("createGroup")
    @ResponseBody
    public Boolean buildGroup(@RequestBody JSONObject json,HttpServletRequest request){
        User user = (User)request.getSession().getAttribute("User");
        Integer selfId = user.getId();
        String temp = String.valueOf(json.get("users")).replace("[","").replace("]","")+","+selfId;
        String ids[] = temp.split(",");
        String tempName = "";
        for(String id : ids){
            tempName += userService.selectUserById(Integer.valueOf(id)).getName()+" ";
        }
        Integer groupId = groupService.searchNextGroupId();
        groupService.setGroupInfo(groupId,tempName);
        for(String id : ids){
            Group group = new Group();
            group.setGroupId(groupId);
            group.setUserId(Integer.valueOf(id));
            groupService.createGroup(group);
        }
        return true;
    }

    @RequestMapping("searchAllGroup")
    @ResponseBody
    public List<GroupInfo> searchAllGroup(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("User");
        Integer userId = user.getId();
        List<Group> groups = groupService.searchAllGroup(userId);
        List<GroupInfo> groupInfos = new ArrayList<GroupInfo>();
        for(Group group :groups){
            GroupInfo tempInfo = groupService.searchGroupName(group.getGroupId());
            if(tempInfo.getName().length() > 15){
                tempInfo.setName(tempInfo.getName().substring(0,15)+"...");
            }
            if(groupService.searchGroupLastMsg(group.getGroupId()).getType().equals("img")){
                tempInfo.setLastMsg("[图片]");
            }else if(groupService.searchGroupLastMsg(group.getGroupId()).getType().equals("file")){
                tempInfo.setLastMsg("[文件]");
            }else{
                tempInfo.setLastMsg(groupService.searchGroupLastMsg(group.getGroupId()).getMsg());
            }
            Integer count = groupService.searchGroupMessageCount(group.getGroupId(),userId).size();
            tempInfo.setUnReadMsgCount(count);
            if(count == 0 ){
                tempInfo.setRedState("none");
            }else{
                tempInfo.setRedState("");
            }
            tempInfo.setUnReadMsgs(groupService.searchGroupMessageCount(group.getGroupId(),userId));
            groupInfos.add(tempInfo);
        }
        return groupInfos;
    }

    @RequestMapping("sendToGroup")
    public void sendToGroup(@RequestBody Chat chat, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("User");
        chat.setFromId(user.getId());
        List<Integer> userIds = groupService.searchUsersInGroup(chat.getGroupId());
        for(Integer userId : userIds){
            if(userId == user.getId()){
                continue;
            }
            chat.setToId(userId);
            if (SessionUtils.hasConnection(userId+"")) {
                chat.setState(0);
                chatService.createChat(chat);
                if ("text".equals(chat.getType())) {
                    JSONObject object = JSONObject.fromObject(chat);
                    System.out.println("toString:"+object.toString());
                    socketHandler.sendMessageToUser(chat.getToId() + "", new TextMessage(object.toString()));
                }
            } else {
                chat.setState(0);
                chatService.createChat(chat);
            }
        }
    }

    @RequestMapping("judgeUserConnection")
    @ResponseBody
    public Boolean judgeUserConnection(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("User");
        System.out.println(user);
        return SessionUtils.hasConnection(user.getId()+"");
    }

    @RequestMapping("sendFileToGroup")
    @ResponseBody
    public String sendFileToGroup(@RequestParam(value = "time") String time, @RequestParam(value = "groupId") Integer groupId, @RequestParam(value = "files") MultipartFile files, HttpServletRequest request) throws Exception {
        User user = (User) request.getSession().getAttribute("User");
        Chat chat = new Chat();
        chat.setTime(time);
        chat.setType("file");
        chat.setFromId(user.getId());
        chat.setGroupId(groupId);
        chat.setIsGroup(1);
        Map<String, String> fileInfo = ChatFileUpLoad.uploadFile(files);
        String filePath = fileInfo.get("filename");
        chat.setMsg(filePath);
        System.out.println(chat.toString());
        List<Integer> userIds = groupService.searchUsersInGroup(chat.getGroupId());
        for(Integer userId : userIds) {
            if (userId == user.getId()) {
                continue;
            }
            chat.setToId(userId);
            if (SessionUtils.hasConnection(chat.getToId() + "")) {
                chat.setState(0);
                chatService.createChat(chat);

                JSONObject object = JSONObject.fromObject(chat);
                if ((chat.getMsg().endsWith(".doc")) || (chat.getMsg().endsWith(".docx"))) {
                    object.put("fileType", "word");
                    object.put("icon", "/zzlp/img/word.jpg");
                } else if (chat.getMsg().endsWith(".xls")) {
                    object.put("fileType", "excel");
                    object.put("icon", "/zzlp/img/excel.jpg");
                } else if (chat.getMsg().endsWith(".txt")) {
                    object.put("fileType", "txt");
                    object.put("icon", "/zzlp/img/txt.jpg");
                } else if ((chat.getMsg().endsWith(".zip")) || (chat.getMsg().endsWith(".rar"))) {
                    object.put("fileType", "zip");
                    object.put("icon", "/zzlp/img/zip.jpg");
                }
                socketHandler.sendMessageToUser(chat.getToId() + "", new TextMessage(object.toString()));
            } else {
                chat.setState(0);
                chatService.createChat(chat);
            }
        }
        JSONObject object1 = JSONObject.fromObject(chat);
        if ((chat.getMsg().endsWith(".doc")) || (chat.getMsg().endsWith(".docx"))) {
            object1.put("fileType", "word");
            object1.put("icon", "/zzlp/img/word.jpg");
        } else if (chat.getMsg().endsWith(".xls")) {
            object1.put("fileType", "excel");
            object1.put("icon", "/zzlp/img/excel.jpg");
        } else if (chat.getMsg().endsWith(".txt")) {
            object1.put("fileType", "txt");
            object1.put("icon", "/zzlp/img/txt.jpg");
        } else if ((chat.getMsg().endsWith(".zip")) || (chat.getMsg().endsWith(".rar"))) {
            object1.put("fileType", "zip");
            object1.put("icon", "/zzlp/img/zip.jpg");
        }
        System.out.println("----" + object1.toString());
        return object1.toString();
    }

    @RequestMapping("sendImgToGroup")
    @ResponseBody
    public String sendImgToGroup(@RequestParam(value = "time") String time, @RequestParam(value = "groupId") Integer groupId, @RequestParam(value = "files") MultipartFile files, HttpServletRequest request) throws Exception {
        User user = (User) request.getSession().getAttribute("User");
        Chat chat = new Chat();
        chat.setTime(time);
        chat.setType("img");
        chat.setFromId(user.getId());
        chat.setGroupId(groupId);
        chat.setIsGroup(1);
        Map<String, String> fileInfo = ChatFileUpLoad.uploadFile(files);
        String filePath = fileInfo.get("filename");
        chat.setMsg(filePath);
        System.out.println(chat.toString());
        List<Integer> userIds = groupService.searchUsersInGroup(chat.getGroupId());
        for(Integer userId : userIds) {
            if (userId == user.getId()) {
                continue;
            }
            chat.setToId(userId);
            if (SessionUtils.hasConnection(chat.getToId() + "")) {
                chat.setState(0);
                chatService.createChat(chat);
                JSONObject object = JSONObject.fromObject(chat);
                socketHandler.sendMessageToUser(chat.getToId() + "", new TextMessage(object.toString()));
            } else {
                chat.setState(0);
                chatService.createChat(chat);
            }
        }
        JSONObject object1 = JSONObject.fromObject(chat);
        System.out.println("----" + object1.toString());
        return object1.toString();
    }

    @RequestMapping("readGroupMessage")
    @ResponseBody
    public Boolean readGroupMessage(@RequestBody Group group,HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("User");
        groupService.readGroupMessage(group.getGroupId(),user.getId());
        return true;
    }

    @RequestMapping("searchUnreadMsgCount")
    @ResponseBody
    public Integer searchUnreadMsgCount(@RequestBody Group group,HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("User");
        return groupService.searchGroupMessageCount(group.getGroupId(),user.getId()).size();
    }

    @RequestMapping("searchUserInfos")
    @ResponseBody
    public List<User_info> searchUserInfos(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("User");
        List<User_info> infos = groupService.searchUserInfos();
        for(int i = 0;i<infos.size();i++){
            if(infos.get(i).getuser_id() == user.getId()){
                User_info temp = infos.get(i);
                infos.set(i,infos.get(0));
                infos.set(0,temp);
                break;
            }
        }
       /* for(int i = 0;i<infos.size();i++){
            System.out.println(infos.get(i).getuser_id()+"\t"+infos.get(i).getPhoto());
        }*/
        return infos;
    }

    @RequestMapping("searchAllGroupMsg")
    @ResponseBody
    public JSONObject searchAllGroupMsg(@RequestBody Group group,HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("User");
        String path = groupService.searchAllGroupMsg(group.getGroupId(),user.getId());
        JSONObject object = new JSONObject();
        object.put("path",path);
        return object;
    }
}
